from pyramid.response import Response
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound
from .models import Student, DBSession


class StudentView:
    def __init__(self, request):
        self.request = request

    @view_config(route_name='list', renderer='./templates/marklist.html')
    def showall(self):
        rows = DBSession.query(Student).all()
        students = []
        for row in rows:
            students.append({"id": row.id, "name": row.name, "percent": row.percent})
        return dict(students=students)

    @view_config(route_name='index', renderer='./templates/myform.html')
    def index(self):
        return {}

    @view_config(route_name='add', request_method='POST')
    def add(self):
        print("add", self.request.POST)
        id = self.request.POST['id']
        name = self.request.POST['name']
        percent = int(self.request.POST['percent'])
        student = Student(id=id, name=name, percent=percent)
        DBSession.add(student)
        # DBSession.commit()
        return HTTPFound(location='http://localhost:6543/')

    @view_config(route_name='show', renderer='./templates/showform.html')
    def show(self):
        print("show", self.request.POST)
        id = self.request.matchdict['id']
        row = DBSession.query(Student).filter(Student.id == id).first()
        student = {'id': row.id, 'name': row.name, 'percent': row.percent}
        return {'student': student}

    @view_config(route_name='update', request_method='POST')
    def update(self):
        print("update", self.request.POST)
        id = int(self.request.POST['id'])
        student = DBSession.query(Student).filter(Student.id == id).first()
        student.percent = int(self.request.POST['percent'])
        # DBSession.commit()
        return HTTPFound(location='http://localhost:6543/')

    @view_config(route_name='delete', renderer='templates/deleted.html')
    def delete(self):
        print("delete", self.request.POST)
        id = self.request.matchdict['id']
        row = DBSession.query(Student).filter(Student.id == id).delete()
        return {'message': 'Redcord has been deleted'}
